/**
 * Title:        HTML模板明细设置检测
 * Company:      泛微软件
 */


package checkDetail;

import general.BaseBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import weaver.conn.RecordSet;
import weaver.general.Util;



public class NodeHtmlLayoutCheck extends BaseBean implements CheckBase  {

    public static String savedids;
    @Override
    public JSONObject checkData(HashMap dataMap) {
        setRecordSet();
        (new BaseBean()).writeLog("SameFieldNameCheck  start");
        List resultList = new ArrayList();
        
        String sqlStr = "";
        sqlStr +=" select top 10 a.id, a.datajson, a.workflowid, a.nodeid, a.layoutname,b.workflowname,c.nodename,b.defaultname ";
        sqlStr +="   from workflow_nodehtmllayout a ";
        sqlStr +="  inner join workflow_base b ";
        sqlStr +="     on b.id = a.workflowid ";
        sqlStr +="  inner join workflow_nodebase c ";
        sqlStr +="     on c.id = a.nodeid ";
        sqlStr +="  where a.version = 2 ";
        sqlStr +=" order by a.workflowid,a.nodeid,a.id ";
        recordSet.executeSql(sqlStr);
        int cnt = 0;
        String nodeids = "";
        while(recordSet.next()){
            nodeids += "," + recordSet.getString("nodeid");
        }
        if(nodeids.startsWith(",")){
            nodeids = nodeids.substring(1);
        }

        //获取节点必填字段
        RecordSet rs = new RecordSet();
        sqlStr = "";
        sqlStr +=" select workflow_nodeform.nodeid,workflow_nodeform.fieldid,workflow_nodebase.isstart  from workflow_nodeform ";
        sqlStr +=" inner join workflow_nodebase on workflow_nodeform.nodeid = workflow_nodebase.id";
        sqlStr +=" where workflow_nodeform.ismandatory = '1' and (" + Util.getSubINClause(nodeids, "nodeid", "in") + ") order by nodeid,fieldid";
        rs.executeSql(sqlStr);
        List<String> fieldidList = new ArrayList<String>();
        String tempnodeid = "";
        Map<String,List> nodeMap = new HashMap<String,List>();
        int cnttemp = 0;
        String isstart = "";
        while(rs.next()){
            String nodeid =  rs.getString("nodeid");
            if(cnttemp > 0 && !nodeid.equals(tempnodeid)){
                if(isstart.equals("1") && fieldidList.indexOf("-1") < 0){
                    fieldidList.add("-1");
                }
                nodeMap.put(tempnodeid,fieldidList);
                fieldidList = new ArrayList<String>();
            }
            fieldidList.add(rs.getString("fieldid"));
            cnttemp++;
            tempnodeid = nodeid;
            isstart = rs.getString("isstart");
        }
        if(cnttemp > 0){
            if(isstart.equals("1") && fieldidList.indexOf("-1") < 0){
                fieldidList.add("-1");
            }
            nodeMap.put(tempnodeid,fieldidList);
        }
        recordSet.beforFirst();
        while(recordSet.next()){
            String datajson = recordSet.getString("datajson");
            String nodeid = recordSet.getString("nodeid");
            String message = checkDatajson(datajson,nodeMap.get(nodeid),recordSet.getString("defaultname").equals("1"));
            if(message.equals("")){
                continue; 
            }else{
                Map resultMap = new HashMap<String,String>();
                savedids +="," + recordSet.getString("id");
                resultMap.put("showMessage","流程[" + recordSet.getString("workflowname") + "]节点[" + recordSet.getString("nodename") + "]的模板[" +  recordSet.getString("layoutname") + "]中存在问题" + message);
                resultMap.put("linkurl","/workflow/workflow/wfnodefieldContent.jsp?ajax=1&wfid=" + recordSet.getString("workflowid") + "&nodeid=" + recordSet.getString("nodeid"));
                resultMap.put("linkname", "设定模板");
                resultList.add(resultMap);
                cnt++;
            }
        }
        if(savedids == null || savedids.equals(""))
            savedids = "-1";
        String msg = "";
        String result = "";
        if(cnt == 0){
            result = resultOk;
        }else{
            result = resultNeedFix;
        }
        (new BaseBean()).writeLog("SameFieldNameCheck  end");
        return formatReturnJsonCheck(result, resultList, this);
    }

    @Override
    public JSONObject fixData(HashMap dataMap) {
        needReload = "1";
        return checkData(new HashMap());
    }
    private String checkDatajson(String jsonstr,List<String> fieldList,boolean defaultName){
        String strMsg = "";
        if(fieldList == null){
            fieldList = new ArrayList<String>(); 
        }
        JSONObject dataJson;
        try {
            dataJson = new JSONObject(jsonstr);
            JSONObject eformdesign = dataJson.getJSONObject("eformdesign");
            JSONObject etables = eformdesign.getJSONObject("etables");
            Iterator<?> it = etables.keys();
            while(it.hasNext()){
                String itkey = it.next().toString();
                String itval = Util.null2String(etables.get(itkey));

                if(itkey.startsWith("emaintable")){
                    JSONObject maintabjson = etables.getJSONObject(itkey);
                    //head长度
                    int colheadslength = Util.getIntValue(maintabjson.getString("colheads"),-1);
                    //head长度
                    int rowheadslength = Util.getIntValue(maintabjson.getString("rowheads"),-1);
                    //有效id列表
                    List<String> mainidList = new ArrayList<String>();
                    for(int rows = 0; rows < rowheadslength; rows++){
                        for(int cols = 0; cols < colheadslength ; cols++){
                            mainidList.add(rows + "," + cols);
                        }
                    }
                    //循环所有单元格
                    JSONArray cells = maintabjson.getJSONArray("ec");

                    for(int i = 0; i < cells.length(); i++){
                        JSONObject cell = cells.getJSONObject(i);
                        String idStr = cell.getString("id");
                        //检测是否存在标签
                        if(mainidList.indexOf(idStr) >= 0){
                            String fieldStr = "";
                            try {
                                fieldStr = cell.getString("field");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            //从必填列表中删除
                            if(fieldList.indexOf(fieldStr) >= 0){
                                fieldList.remove(fieldList);
                            }
                        }
                    }
                }
                if(itkey.startsWith("detail_")){
                    JSONObject detailjson = etables.getJSONObject(itkey);
                    //表尾标示
                    int edtailinrow = Util.getIntValue(detailjson.getString("edtailinrow"),-1);
                    //表头标示
                    int edtitleinrow = Util.getIntValue(detailjson.getString("edtitleinrow"),-1);
                    int seniorset = -1;
                    try {
                        seniorset = Util.getIntValue(detailjson.getString("seniorset"),-1);
                    } catch (JSONException e) {
                    }
                    if(seniorset != 1 && edtailinrow-edtitleinrow != 2){
                        strMsg += "[非高级定制模式，明细中有多行]";
                    }else if(seniorset != 1 && edtailinrow-edtitleinrow <= 1){
                        strMsg += "[高级定制模式，没有明细行]";
                    }
                    //head长度
                    int colheadslength = detailjson.getJSONObject("colheads").length();
                    //有效id列表
                    List<String> idList = new ArrayList<String>();
                    for(int rows = edtitleinrow + 1; rows < edtailinrow; rows++){
                        for(int cols = 0; cols < colheadslength ; cols++){
                            idList.add(rows + "," + cols);
                        }
                    }
                    //循环所有单元格
                    JSONArray cells = detailjson.getJSONArray("ec");
                    for(int i = 0; i < cells.length(); i++){
                        JSONObject cell = cells.getJSONObject(i);
                        String idStr = cell.getString("id");
                        String fieldStr = "";
                        //检测是否存在标签
                        if(idList.indexOf(idStr) >= 0){
                            try {
                                fieldStr = cell.getString("field");
                            } catch (JSONException e) {
                            }
                            //从必填列表中删除
                            if(fieldList.indexOf(fieldStr) >= 0){
                                fieldList.remove(fieldList);
                            }
                            if(cell.getString("etype") != null && cell.getString("etype").equals("2")){
                                strMsg += "[明细中存在标签]";
                            }
                        }
                    }
                }else{
                    continue;
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if(fieldList.size() > 0){
            if(fieldList.indexOf("-1") >= 0){
                if(!defaultName){
                    strMsg += "[标题字段没有放到表单中，而且没有设置默认标题]";
                }
                fieldList.remove("-1");
            }
        }
        if(fieldList.size() > 0){
            strMsg += "[有必填字段没有放到表单中]";
        }
        return strMsg;
        
    }

    @Override
    public String getClassName() {
        return "HTML模板明细设置检测";
    }

    @Override
    public String getClassDesc() {
        return "检测html模板设置，表头及表尾标识中是否存在多行（低级定制模式），是否存在标签";
    }
}
